//
//  ConfigManager.cpp
//  BayMaxPuzzle
//
//  Created by Jacky on 15/3/29.
//
//

#include "ConfigManager.h"
#include "EncryptUserDefault.h"

ConfigManager* ConfigManager::m_pInstance = nullptr;
ConfigManager::CGarbo ConfigManager::m_garbo;

ConfigManager::ConfigManager()
{
}

void ConfigManager::readConfig()
{
    if (isHaveSaveFile())
    {
        for (int i=0; i<CHAPTER; i++) {
            for (int j=0; j<SECTION; j++) {
                char buffer[20];
                sprintf(buffer, "level_%02d_%02d", i,j);
                _score[i][j] = EncryptUserDefault::getInstance()->getIntegerForKey(buffer);
            }
        }
    }
}

void ConfigManager::initConfig()
{
    for (int i=0; i<CHAPTER; i++) {
        for (int j=0; j<SECTION; ++j)
        {
            char buffer[20];
            sprintf(buffer, "level_%02d_%02d", i,j);
            EncryptUserDefault::getInstance()->setIntegerForKey(buffer, 0);
            _score[i][j] = 0;
        }
    }
    EncryptUserDefault::getInstance()->setBoolForKey("isHaveSaveFileXml", true);
    EncryptUserDefault::getInstance()->flush();
}

void ConfigManager::saveConfig()
{
    for (int i=0; i<CHAPTER; i++) {
        for (int j=0; j<SECTION; ++j)
        {
            char buffer[20];
            sprintf(buffer, "level_%02d_%02d", i,j);
            EncryptUserDefault::getInstance()->setIntegerForKey(buffer, _score[i][j]);
        }
    }
    EncryptUserDefault::getInstance()->setBoolForKey("isHaveSaveFileXml", true);
    EncryptUserDefault::getInstance()->flush();
}

int ConfigManager::getConfig(int chapter, int section)
{
    if (chapter>=CHAPTER || section>=SECTION) {
        CCLOG("Out of range.");
        return 0;
    }
    return _score[chapter][section];
}

void ConfigManager::setConfig(int chapter, int section, int score)
{
    if (chapter>=CHAPTER || section>=SECTION) {
        CCLOG("Out of range.");
    }
    _score[chapter][section] = score;
    saveConfig();
}



bool ConfigManager::isHaveSaveFile()
{
    if(!EncryptUserDefault::getInstance()->getBoolForKey("isHaveSaveFileXml"))
    {
        initConfig();
        
        return false;
    }
    else return true;
}

void ConfigManager::dumpAllConfig()
{
    for (int i=0; i<CHAPTER; i++) {
        for (int j=0; j<SECTION; ++j)
        {
            CCLOG("chapter:%d, section:%d, score:%d", i, j, _score[i][j]);
        }
    }
}
